//
//  JoFileUpload.swift
//  JoTravel
//
//  Created by otisaldridge on 15/9/25.
//  Copyright © 2015年 zhuxietong. All rights reserved.

import Foundation
import UIKit
import Foundation
import Alamofire





public protocol JoTaskServerImplement:NSObjectProtocol{
    func start(task:JoTask,respones:@escaping (ResponseStatus, Any, String) -> Void)
}

public class JoTaskServerDemo:NSObject,JoTaskServerImplement{
    public static var share = JoTaskServerDemo()
    var index = 0
    public func start(task: JoTask, respones:@escaping (ResponseStatus, Any, String) -> Void) {
            
        let params = task.getParams().mutable_dictionary
        let k = params[PageConfig.page_key,""].IntV
        let num = PageConfig.default_page_size
        if k < 3{
            co_delay(delay: 1) {
                respones(.success,SandBox.section(count: num),"获取数据成功")
            }
        }else{
            co_delay(delay: 1) {
                respones(.success,SandBox.section(count: 1),"获取数据成功")
            }
        }
        
        
    }
}

public func _ArrayTsk(_ key:String,_ task:JoTask) -> JoTask_<NSMutableArray> {
    return JoTask_<NSMutableArray>(key: key, task: task)
}

public func _DictTsk(_ key:String,_ task:JoTask) -> JoTask_<NSMutableDictionary> {
    return JoTask_<NSMutableDictionary>(key: key, task: task)
}
open class JoTask_<T:RootData>:OneJoTask{
    open override func startTask() {
        task.json_handle { [weak self](status, msg, obj, resp, tsk) in
            HUD.share.hide(animated: true)
            if status.isSuccess{
                if let result = obj as? T{
                    self?.result = result
                    self?.finish(success: true, objs: result)
                }
                return
            }
            self?.errorStr = msg
            self?.finish(success: false, objs: msg)
        }.run()
    }
}

open class OneJoTask:NSObject,AsyncTask{
    
    public let task:JoTask
    public let key:String
    public var errorStr:String = ""
    
    public var result:RootData? = nil
    public init(key:String,task:JoTask) {
        self.task = task
        self.key = key
    }
    //-------AsyncTask start ------

    public var asyncQueIndex: Int = 0
    
    public var asyncStatus: TaskStatus = .waiting
    
    public var asyncDelegate: AsyncTaskDelegate? = nil
    
    
    open func startTask() {
      
//        fatalError("请完善 startTask 逻辑才内进行异步上传")
    }
    public func canleTask() {
        self.finish(success: false, objs: "已取消")
    }
    public func finish(success: Bool, objs: Any...) {
        if success{
            self.asyncStatus = .success
        }
        else{
            self.asyncStatus = .failed
        }
        asyncDelegate?.finish(task: self)
    }
    
    //-------AsyncTask end------
        
}



public class KVTask:NSObject,JoTaskServerImplement{
    
    public struct KVTaskResult{
        public let key:String
        public let obj:Any
        public let task:JoTask
        
        
        
    }
    public let tasks:[String:JoTask]
    public init(tasks:[String:JoTask]) {
        self.tasks = tasks
        super.init()
    }
    public func start(task: JoTask, respones: @escaping (ResponseStatus, Any, String) -> Void) {
        var tasks_:[(String,JoTask)] = []
        for (k,v) in tasks {
            tasks_.append((k,v))
        }
        tasks_.async { (item, i, task:Array.AsyncTask<KVTaskResult>) in
            item.1.json_handle { status, msg, obj, resp, tsk in
                if status.isSuccess{
                    task.success(.init(key: item.0, obj: obj, task: item.1))
                }else{
                    task.error(msg)
                }
            }.run()
        } finish: { r in
            let result = NSMutableDictionary()
            for item in r{
                result[item.key] = item.obj
            }
            respones(.success,result,"数据加载成功")

        } error: { err in
            task.resultTip = ._error(tip: err, tag: nil)
            respones(.error,NSMutableArray(),err)
        }

    }
}

open class MutilJoTask:NSObject,JoTaskServerImplement{

    public var tasks:[OneJoTask] = []
    public init(tasks:[OneJoTask]) {
        super.init()
        self.tasks = tasks
        
    }
    
    open var result:NSMutableDictionary{
        let dict = NSMutableDictionary()
        for t in tasks {
            if let r = t.result{
                dict[t.key] = r
            }
        }
        return dict
    }
    open func start(task: JoTask, respones:@escaping (ResponseStatus, Any, String) -> Void) {
        


        
        AsyncQue.default.start(tasks:tasks) {[weak self](progress) in
           DispatchQueue.main.async(execute: {
               switch progress  {
               case .failed(count: _, task: let t):
                DispatchQueue.main.async(execute: {
                    if let err = (t as? OneJoTask)?.task.resultTip{
                        task.resultTip = err
                    }

                    respones(.error,NSMutableArray(),(t as? OneJoTask)?.errorStr ?? "未知错误")
                })
               case .success:
                   DispatchQueue.main.async(execute: {
                    guard let ws = self else{return}
                    respones(.success,ws.result,"数据请求成功")
                   })
               case .continue(count: _, task:_):
                   break
               }
           })
       }
        

    }
}
